package com.monkey.web.shiro.web.filter.user;

import com.monkey.core.web.ServletRequestContextHolder;
import com.monkey.core.web.response.MonkeyResponseDto;
import com.monkey.core.web.response.ResponseCode;
import com.monkey.utils.WebUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class AppUserFilter extends UserFilter {

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        //把request对象放入到ThreadLocal
        ServletRequestContextHolder.setRequest(request);
        if (isLoginRequest(request, response)) {
            return true;
        } else {
            Subject subject = getSubject(request, response);
            return subject.getPrincipal() != null;
        }
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        MonkeyResponseDto responseDto = new MonkeyResponseDto();
        responseDto.fail(ResponseCode.NOT_LOGIN, "用户还未登录");
        WebUtils.writeJSON(response, responseDto);
        return false;
    }

}
